package com.mt.demo.service.impl;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.mt.demo.manager.MeetingRoomManager;
import com.mt.demo.manager.MeetingUserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class HeartbeatService {
    @Autowired
    private SocketIOServer socketIOServer;

    @Autowired
    private MeetingRoomManager meetingRoomManager;

    @Autowired
    private MeetingUserManager meetingUserManager;

    @Autowired
    private ScreenSharingService screenSharingService;

    private static final long HEARTBEAT_TIMEOUT = 30000; // 30秒超时

    // 处理客户端心跳
    public void handleHeartbeat(SocketIOClient client) {
        String clientId = client.getSessionId().toString();
        String roomId = client.getHandshakeData().getSingleUrlParam("roomId");
        
        // 更新客户端最后心跳时间
        meetingRoomManager.updateClientHeartbeat(clientId);
        
        // 发送心跳响应
        client.sendEvent("pong");
    }

    // 每30秒检查一次心跳超时
    @Scheduled(fixedRate = 30000)
    public void checkHeartbeatTimeout() {
        long currentTime = System.currentTimeMillis();
        
        // 遍历所有房间的客户端
        socketIOServer.getAllClients().forEach(client -> {
            String clientId = client.getSessionId().toString();
            String roomId = client.getHandshakeData().getSingleUrlParam("roomId");
            String userId = client.getHandshakeData().getSingleUrlParam("userId");
            
            Long lastHeartbeat = meetingRoomManager.getClientLastHeartbeat(clientId);
            if (lastHeartbeat != null && (currentTime - lastHeartbeat > HEARTBEAT_TIMEOUT)) {
                handleClientTimeout(client, roomId, userId);
            }
        });
    }

    // 处理客户端超时
    private void handleClientTimeout(SocketIOClient client, String roomId, String userId) {
        // 清理屏幕共享状态
        screenSharingService.cleanupUserScreenSharing(roomId, userId);
        
        // 从房间移除客户端
        meetingRoomManager.removeClientFromRoom(roomId, client);
        
        // 从在线用户列表移除
        meetingUserManager.removeOnlineUser(roomId, userId);
        
        // 通知房间其他用户
        meetingRoomManager.getRoomClients(roomId).forEach(roomClient -> {
            if (!roomClient.getSessionId().equals(client.getSessionId())) {
                roomClient.sendEvent("userTimeout", userId);
            }
        });
        
        // 断开客户端连接
        client.disconnect();
    }

    // 检查客户端是否活跃
    public boolean isClientActive(String clientId) {
        Long lastHeartbeat = meetingRoomManager.getClientLastHeartbeat(clientId);
        return lastHeartbeat != null && 
               (System.currentTimeMillis() - lastHeartbeat <= HEARTBEAT_TIMEOUT);
    }
}
